<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工程名称" prop="jiesuanListName">
        <el-input
          v-model="queryParams.jiesuanListName"
          placeholder="请输入工程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="jiesuanState">
        <el-select
          v-model="queryParams.jiesuanState"
          placeholder="请选择状态"
          clearable
          @change="handleQuery"
        >
          <el-option label="所有状态" value=""></el-option>
<!--          <el-option label="草稿" value="1"></el-option>-->
          <el-option label="已上传" value="2"></el-option>
          <el-option label="已生成" value="3"></el-option>
<!--          <el-option label="已退回" value="4"></el-option>-->
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="addTime">
        <el-row>
          <el-col :span="11">
            <el-date-picker
              v-model="queryParams.startDate"
              type="date"
              placeholder="开始日期"
              value-format="yyyy-MM-dd"
              clearable
              style="width: 100%;"
            />
          </el-col>
          <el-col :span="2" class="text-center">
            <span>至</span>
          </el-col>
          <el-col :span="11">
            <el-date-picker
              v-model="queryParams.endDate"
              type="date"
              placeholder="结束日期"
              value-format="yyyy-MM-dd"
              clearable
              style="width: 100%;"
            />
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--&lt;!&ndash;      <el-col :span="1.5">&ndash;&gt;-->
<!--&lt;!&ndash;        <el-button&ndash;&gt;-->
<!--&lt;!&ndash;          type="danger"&ndash;&gt;-->
<!--&lt;!&ndash;          plain&ndash;&gt;-->
<!--&lt;!&ndash;          icon="el-icon-delete"&ndash;&gt;-->
<!--&lt;!&ndash;          size="mini"&ndash;&gt;-->
<!--&lt;!&ndash;          :disabled="!ids.length"&ndash;&gt;-->
<!--&lt;!&ndash;          @click="handleBatchDelete"&ndash;&gt;-->
<!--&lt;!&ndash;          v-hasPermi="['custJiesuanList:custJiesuanList:remove']"&ndash;&gt;-->
<!--&lt;!&ndash;        >批量删除&ndash;&gt;-->
<!--&lt;!&ndash;        </el-button>&ndash;&gt;-->
<!--&lt;!&ndash;      </el-col>&ndash;&gt;-->


<!--      <el-col :span="1.5">-->
<!--&lt;!&ndash;        <el-button&ndash;&gt;-->
<!--&lt;!&ndash;          type="info"&ndash;&gt;-->
<!--&lt;!&ndash;          plain&ndash;&gt;-->
<!--&lt;!&ndash;          icon="el-icon-upload2"&ndash;&gt;-->
<!--&lt;!&ndash;          size="mini"&ndash;&gt;-->
<!--&lt;!&ndash;          @click="handleImport"&ndash;&gt;-->
<!--&lt;!&ndash;          v-hasPermi="['custJiesuanList:custJiesuanList:import']"&ndash;&gt;-->
<!--&lt;!&ndash;        >导入&ndash;&gt;-->
<!--&lt;!&ndash;        </el-button>&ndash;&gt;-->
<!--        <input-->
<!--          type="file"-->
<!--          style="display:none;"-->
<!--          ref="fileInput"-->
<!--          accept=".xlsx,.xls"-->
<!--          @change="onFileSelected"-->
<!--        />-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="custJiesuanListList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="结算单明细的id" align="center" prop="jiesuanListId" />-->
      <!--            <el-table-column label="结算单的id" align="center" prop="jiesuanId" />-->
      <!--      <el-table-column label="结算单的日期" align="center" prop="jiesuanTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.jiesuanTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="日期" align="center" width="180">
        <template slot-scope="scope">
          <!-- 检查 custJiesuanLists 是否存在且不为空 -->
          <span v-if="scope.row.custJiesuanLists && scope.row.custJiesuanLists.length > 0">
      {{ parseTime(scope.row.custJiesuanLists[0].jiesuanTime, '{y}-{m}-{d}') }}
    </span>
          <!-- 如果不存在或为空，则可以显示默认值或提示信息 -->
          <span v-else>
      无明细记录
    </span>
        </template>
      </el-table-column>
      <el-table-column label="工程名称" align="center" prop="projectName"/>
      <el-table-column label="状态" align="center" prop="jiesuanState">
        <template slot-scope="scope">
          <!-- 显示状态对应的中文名称 -->
          <span>
        {{ getStatusText(scope.row.jiesuanState) }}
      </span>
        </template>
      </el-table-column>
      <el-table-column label="工程量" align="center" prop="gongchengliang">
        <template slot-scope="scope">
          <!-- 检查 custJiesuanLists 是否存在且不为空 -->
          <span v-if="scope.row.custJiesuanLists && scope.row.custJiesuanLists.length > 0">
      {{ scope.row.custJiesuanLists[0].gongchengliang }}
    </span>
          <!-- 如果不存在或为空，则可以显示默认值或提示信息 -->
          <span v-else>
      无记录
    </span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="单位" align="center" prop="danwei"/>-->
      <el-table-column label="单位" align="center" prop="danwei">
        <template slot-scope="scope">
          <!-- 检查 custJiesuanLists 是否存在且不为空 -->
          <span v-if="scope.row.custJiesuanLists && scope.row.custJiesuanLists.length > 0">
      {{ scope.row.custJiesuanLists[0].danwei }}
    </span>
          <!-- 如果不存在或为空，则可以显示默认值或提示信息 -->
          <span v-else>
      无记录
    </span>
        </template>

      </el-table-column>
      <!--      <el-table-column label="单价" align="center" prop="danjia"/>-->
      <!--      <el-table-column label="合价" align="center" prop="hejia"/>-->
      <!--      <el-table-column label="创建时间" align="center" prop="addTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.addTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"

          >查看详情
          </el-button>
          <!-- 确认提交按钮 -->
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.jiesuanState === 2"
            icon="el-icon-check"
            @click="handleConfirmSubmit(scope.row)"
          >确认
          </el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.jiesuanState === 2"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >退回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改结算单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="jiesuanTime">
          <template slot-scope="scope">
            <!-- 如果 custJiesuanLists 存在且非空，则取第一个元素的 jiesuanTime -->
            <span v-if="form.custJiesuanLists && form.custJiesuanLists.length > 0">
          {{ parseTime(form.custJiesuanLists[0].jiesuanTime, '{y}-{m}-{d}') }}
        </span>
            <!-- 如果不存在或为空，则显示提示信息 -->
            <span v-else>
          无明细记录
        </span>
          </template>
        </el-form-item>
        <el-form-item label="工程名称" prop="jiesuanListName">
          <span>{{ form.projectName || '无' }}</span>
        </el-form-item>
        <el-form-item label="工程量" prop="gongchengliang">
          <template slot-scope="scope">
            <!-- 检查 custJiesuanLists 是否存在且不为空 -->
            <span v-if="form.custJiesuanLists && form.custJiesuanLists.length > 0">
      {{ form.custJiesuanLists[0].gongchengliang }}
    </span>
            <!-- 如果不存在或为空，则可以显示默认值或提示信息 -->
            <span v-else>
      无记录
    </span>
          </template>
        </el-form-item>
        <el-form-item label="单位" prop="danwei">
          <template slot-scope="scope">
            <!-- 检查 custJiesuanLists 是否存在且不为空 -->
            <span v-if="form.custJiesuanLists && form.custJiesuanLists.length > 0">
      {{ form.custJiesuanLists[0].danwei }}
    </span>
            <!-- 如果不存在或为空，则可以显示默认值或提示信息 -->
            <span v-else>
      无记录
    </span>
          </template>
        </el-form-item>
        <!--        <el-form-item label="单价" prop="danjia">-->
        <!--          <span>{{ form.danjia || '无' }}</span>-->
        <!--        </el-form-item>-->
        <el-form-item label="材料" prop="hejia">
          <div v-if="form.custJiesuanLists && form.custJiesuanLists.length > 1">
            <div v-for="(item, index) in form.custJiesuanLists.slice(1)" :key="index">
              <span>{{ item.jiesuanListName || '无记录' }} -- {{ item.gongchengliang || '' }} {{
                  item.danwei || ''
                }}</span><br/>

            </div>
          </div>
          <div v-else>
            <span>无记录</span>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listCustJiesuanList,
  getCustJiesuanList,
  delCustJiesuanList,
  addCustJiesuanList,
  updateCustJiesuanList, listCustJiesuanListByConfirm, outCustJiesuanList
} from "@/api/custJiesuanList/custJiesuanList";
import axios from 'axios';


export default {
  name: "CustJiesuanList",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 结算单表格数据
      custJiesuanListList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      file: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jiesuanId: null,
        jiesuanTime: null,
        jiesuanListName: null,
        gongchengliang: null,
        danwei: null,
        danjia: null,
        hejia: null,
        addTime: null,
        jiesuanState: '',
        startDate: null,  // 开始日期
        endDate: null,    // 结束日期
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询结算单列表 */
    getList() {
      this.loading = true;
      listCustJiesuanListByConfirm(this.queryParams).then(response => {
        this.custJiesuanListList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getStatusText(state) {
      switch (state) {
        case 1:
          return '草稿';
        case 2:
          return '已上传';
        case 3:
          return '已生成';
        case 4:
          return '已退回';
        default:
          return '未知状态'; // 如果状态值不在 1-4 范围内，可以返回 '未知状态'
      }
    },
    /** 确认提交 */
    handleConfirmSubmit(row) {
      const jiesuanId = row.jiesuanId;

      // 弹出确认框
      this.$modal.confirm('是否确认').then(() => {
        // 用户点击确认后，提交数据
        this.submitData(jiesuanId);
      }).catch(() => {
        // 用户点击取消时，不做任何处理
        this.$modal.msgInfo('操作已取消');
      });
    },
    /** 提交数据 */
    submitData(jiesuanId) {
      // 在这里实现你提交数据的逻辑，可以通过 API 调用后端接口
      axios.post('/dev-api/custJiesuanList/custJiesuanList/confirmSubmit', {jiesuanId}).then(response => {
        this.$modal.msgSuccess('确认提交成功');
        this.getList(); // 刷新列表
      }).catch(error => {
        this.$modal.msgError('提交失败');
      });
    },
    // 表单重置
    reset() {
      this.form = {
        jiesuanListId: null,
        jiesuanId: null,
        jiesuanTime: null,
        jiesuanListName: null,
        gongchengliang: null,
        danwei: null,
        danjia: null,
        hejia: null,
        addTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jiesuanId)
      console.log(this.ids)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加结算单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      const jiesuanId = row.jiesuanId || this.ids
      getCustJiesuanList(jiesuanId).then(response => {
        this.form = response.data;
        console.log(this.form);
        this.open = true;
        this.title = "查看结算单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.jiesuanListId != null) {
            updateCustJiesuanList(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustJiesuanList(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    handleDelete(row) {
      const jiesuanId = row.jiesuanId || this.ids;
      this.$modal.confirm('是否确认退回').then(function () {
        return outCustJiesuanList(jiesuanId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("退回成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('custJiesuanList/custJiesuanList/export', {
        ...this.queryParams
      }, `custJiesuanList_${new Date().getTime()}.xlsx`)
    },
    handleImport() {
      this.$refs.fileInput.click(); // 触发文件选择
    },

    /** 文件选择事件处理 */
    onFileSelected(event) {
      const selectedFile = event.target.files[0];
      if (selectedFile) {
        this.file = selectedFile;
        this.uploadFile();
      }
    },

    /** 文件上传逻辑 */
    uploadFile() {
      const formData = new FormData();
      formData.append('file', this.file);

      axios.post('/dev-api/custJiesuanList/custJiesuanList/upload1', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        // 处理成功响应
        this.$message.success('文件上传成功');
        this.getList(); // 刷新列表
      }).catch(error => {
        // 处理错误
        console.error('文件上传失败:', error);
        this.$message.error('文件上传失败');
      });
    },
    handleBatchDelete() {
      if (this.ids.length === 0) {
        this.$message.warning('请选择至少一条记录');
        return;
      }

      this.$modal.confirm('是否确认删除选中的记录').then(() => {
        delCustJiesuanList(this.ids).then(() => {
          console.log(this.ids)
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
          this.$modal.msgError("删除失败");
        });
      }).catch(() => {
      });
    },

  },


};
</script>
